package com.ruoyi.web.controller.system;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.IAgentRelationshipService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.IAgentService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 中介Controller
 * 
 * @author ruoyi
 * @date 2021-03-14
 */
@Controller
@RequestMapping("/system/agent")
public class AgentController extends BaseController
{
    private String prefix = "system/agent";

    @Autowired
    private IAgentService agentService;
    @Autowired
    private IAgentRelationshipService agentRelationshipService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDictDataService sysDictDataService;

    @RequiresPermissions("system:agent:view")
    @GetMapping()
    public String agent()
    {
        return prefix + "/agent";
    }

    /**
     * 查询中介列表
     */
    @RequiresPermissions("system:agent:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Agent agent)
    {
        startPage();
        agent.setGuest("1");
        List<Agent> list = agentService.selectAgentList(agent);
        for(Agent ag:list){
            SysUser sysUser = sysUserService.selectUserById(ag.getUserId());
            if(sysUser!=null){
                ag.setUserName(sysUser.getUserName());
            }
            AgentRelationship agentRelationship = new AgentRelationship();
            agentRelationship.setAgentId(ag.getId());
            List<AgentRelationship> agentRelationships = agentRelationshipService.selectAgentRelationshipList(agentRelationship);
            if(agentRelationships.size()>0){
                String rinfo = sysDictDataService.selectDictLabel("relationship_info", agentRelationships.get(agentRelationships.size()-1).getRelationshipInfo());
                String rcont = agentRelationships.get(agentRelationships.size()-1).getRelationshipResult();
                if(StringUtils.isNotBlank(rcont)){
                    rinfo = rinfo+"-"+rcont;
                }
                ag.setRecord(rinfo+"("+ DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",(Date)(agentRelationships.get(agentRelationships.size()-1).getCreateTime()))+")");
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出中介列表
     */
    @RequiresPermissions("system:agent:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Agent agent)
    {
        agent.setGuest("1");
        PageHelper.startPage(1, 99999999, "relation_time desc");
        List<Agent> list = agentService.selectAgentList(agent);
        for(Agent ag:list){
            SysUser sysUser = sysUserService.selectUserById(ag.getUserId());
            if(sysUser!=null){
                ag.setUserName(sysUser.getUserName());
            }
        }
        ExcelUtil<Agent> util = new ExcelUtil<Agent>(Agent.class);
        return util.exportExcel(list, "agent");
    }

    /**
     * 新增中介
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存中介
     */
    @RequiresPermissions("system:agent:add")
    @Log(title = "中介", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Agent agent)
    {
        Agent agentParam = new Agent();
        agentParam.setTelephone(agent.getTelephone());
        List<Agent> agents = agentService.selectAgents(agentParam);
        if(agents.size()>0){
            return AjaxResult.error("手机号已存在！");
        }
        agent.setUserId(ShiroUtils.getUserId());
        agent.setDeptId(ShiroUtils.getSysUser().getDeptId());
        agent.setRelationTime(DateUtils.getNowDate());
        return toAjax(agentService.insertAgent(agent));
    }

    /**
     * 修改中介
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        Agent agent = agentService.selectAgentById(id);
        mmap.put("agent", agent);
        return prefix + "/edit";
    }

    /**
     * 修改保存中介
     */
    @RequiresPermissions("system:agent:edit")
    @Log(title = "中介", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Agent agent)
    {
        Agent agentOld = agentService.selectAgentById(agent.getId());
        Agent agentParam = new Agent();
        agentParam.setTelephone(agent.getTelephone());
        List<Agent> agents = agentService.selectAgents(agentParam);
        if(!agentOld.getTelephone().equals(agent.getTelephone())&&agents.size()>0){
            return AjaxResult.error("手机号已存在！");
        }
        agent.setRelationTime(DateUtils.getNowDate());
        return toAjax(agentService.updateAgent(agent));
    }

    /**
     * 删除中介
     */
    @RequiresPermissions("system:agent:remove")
    @Log(title = "中介", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(agentService.deleteAgentByIds(ids));
    }

    /**
     * 联系记录
     */
    @GetMapping("/relationshipRecord/{id}")
    public String relationshipRecord(@PathVariable("id") Long id, ModelMap mmap)
    {
        Agent agent = agentService.selectAgentById(id);
        mmap.put("agent", agent);
        return "system/relationship/relationship";
    }

    /**
     * 加载系统用户
     */
    @GetMapping("/getSysUserList")
    @ResponseBody
    public List<SysUser> getSysUserList()
    {
        SysUser sysUser = new SysUser();
        List<SysUser> sysUserList = sysUserService.selectUserList(sysUser);
        return sysUserList;
    }

    /** 移交客户 **/
    @GetMapping(value = "/changeUser/{ids}")
    public String changeUser(@PathVariable(value = "ids", required = true) String ids, ModelMap mmap)
    {
        mmap.put("ids", ids);
        return prefix + "/change_user";
    }

    @PostMapping("/changeAgentUser")
    @ResponseBody
    public AjaxResult changeAgentUser(@RequestParam(value = "ids", required = true) String ids, @RequestParam(value = "userId", required = true) Long userId)
    {
        for(String id:ids.split(",")){
            Agent agent = agentService.selectAgentById(Long.parseLong(id));
            agent.setUserId(userId);
            agent.setDeptId(sysUserService.selectUserById(userId).getDeptId());
            agentService.updateAgent(agent);
        }
        return toAjax(1);
    }

    /** 统计分析 **/
    @GetMapping(value = "/analysize")
    public String analysize()
    {
        return prefix + "/analysize";
    }

    /**
     * 查询统计
     */
    @PostMapping("/analysizeList")
    @ResponseBody
    public TableDataInfo analysizeList(Analyse analyse)
    {
        startPage();
        List<Analyse> list = agentService.selectAnalysizeList(analyse);
        for(Analyse ana:list){
            SysUser sysUser = sysUserService.selectUserById(ana.getUserId());
            if(sysUser!=null){
                ana.setUserName(sysUser.getUserName());
            }
        }
        return getDataTable(list);
    }
}
